package com.hlk.article.html.controller;

import com.hlk.controller.article.ArticleHTMLControllerApi;
import com.mongodb.client.gridfs.GridFSBucket;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

/**
 * @author hlk
 * @version 1.0
 * @date 2020-12-30 15:02
 */
@RestController
public class ArticleHtmlController implements ArticleHTMLControllerApi {

    @Value("${freemarker.target.article}")
    private String targetPath;
    @Autowired
    private GridFSBucket gridFSBucket;


    @Override
    public Integer download(String articleId, String articleMongoId) throws Exception {
        String path = targetPath + File.separator + articleId + ".html";

        File file = new File(path);

        gridFSBucket.downloadToStream(new ObjectId(articleMongoId), new FileOutputStream(file));

        return HttpStatus.OK.value();
    }

    @Override
    public Integer delete(String articleId) throws Exception {
        String path = targetPath + File.separator + articleId + ".html";
        File file = new File(path);
        file.delete();
        return HttpStatus.OK.value();
    }
}
